package service

import (
	"fmt"
	"git.oschina.net/fanbuchi/redpack/database"
	"git.oschina.net/fanbuchi/redpack/domain"
	"git.oschina.net/fanbuchi/redpack/errors"
)
type RedPackService struct {
}


func  (service*RedPackService)Create(params *domain.RedPack)(*domain.RedPack,error)  {
	//validate
	if params.Fee<=0 || params.Amount==0 {
		 return nil,_error.ErrAccountNull
	}
	params.ID=0
	//
	err := database.Master().Create(params).Error
	if  err != nil {
		return nil,err
	}
	return params,nil
}

func  (service*RedPackService)Delete1ById(id int64)(*domain.RedPack,error)     {
	params:=domain.RedPack{ID:id}
	err:=database.Master().Delete(params).Error
	if err!=nil {
		return nil,err
	}
	return &params,nil
}

func  (service*RedPackService)Update(params *domain.RedPack)(*domain.RedPack,error)     {
	err:=database.Master().Update(params).Error
	if err!=nil {
		return nil,err
	}
	return params,err
}


func  (service*RedPackService)Query1ByUserName(userName string)(*domain.Account,error)  {
	if userName==""{
		return nil,_error.ErrAccountNull
	}
	var result domain.Account
	 err := database.Master().
		Where("user_name=?",userName).
		Omit("password").
	 	First(result).
	 	Error
	if err != nil {
		return nil,err
	}
	return &result,nil
}

//根据id查询一条数据
func  (service*RedPackService)Query1ById(id int64)(*domain.RedPack,error)  {
	result:=domain.RedPack{ID:id}
	err := database.Master().First(result).Error
	if  err != nil {
		return nil,err
	}
	return &result,nil
}

func  (service*RedPackService)Search(params *domain.RedPack,page int,size int)([]*domain.RedPack,error)  {
	list := make([]*domain.RedPack, 0)
	/*err := database.Master().
		Select("red_packs.*,profiles.nick_name as account_name" +
			",profiles.head_file as head_file"+
			",profiles.slogan as slogan").
		Where(params).
		Joins("left join profiles on profiles.account_id = red_packs.account_id ").
		Limit(size).
		Offset((page-1)*size).
		Find(&list).
		Error*/
	lat:=params.Latitude
	lon:=params.Longitude
	//SELECT id, xxxx FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0, 20;
	selects:="red_packs.*,( 3959 * acos( cos( radians('%f') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('%f') ) + sin( radians('%f') ) * sin( radians( latitude ) ) ) ) AS distance"
	format:=fmt.Sprintf(selects,lat,lon,lat)
	params.Latitude=0
	params.Longitude=0
	err :=database.Master().
		Select(format).
		Where(params).
		Having("distance < 250000").
		Order("distance").
		Limit(size).
		Offset((page-1)*size).
		Preload("Profile").
		Find(&list).Error
	return list,err
}




